//
//  CardOfferViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2019/1/8.
//  Copyright © 2019年 DUONIU_MAC. All rights reserved.
//

import UIKit
import WebKit

class CardOfferViewController: KMViewController {
    
    fileprivate var urlStr = ""
    
    //需要移除的标签
    var removeElements = [String]()
    var removeIds = [String]()
    
    ///webview
    fileprivate var webView : WKWebView!
    ///进度条
    fileprivate let progressView = UIProgressView()
    
    init(urlStr:String,title:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.urlStr = urlStr
        self.title = title
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        
        self.view.backgroundColor = UIColor.white
        
        progressView.trackTintColor = UIColor.clear
        progressView.progressTintColor = UIColor.moveColor()
        self.view.addSubview(progressView)
        
        progressView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 5))
        }
        
        createWebView()
        
        self.view.bringSubview(toFront: progressView)

    }
    
    deinit {
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
        self.webView.removeObserver(self, forKeyPath: "title")
    }
    
    fileprivate func createWebView() {
        
        self.webView = WKWebView.init(frame: .zero)
        //路径编码
        let string = self.urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        if let url = URL.init(string: string ?? "") {
            let request = URLRequest.init(url: url)
            webView.load(request)
        }
        webView.navigationDelegate = self
        webView.uiDelegate = self
        self.view.addSubview(webView)
        
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        self.webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        
        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if "estimatedProgress" == keyPath {
            self.progressView.setProgress(Float(self.webView.estimatedProgress), animated: true)
            if self.progressView.progress == 0 {
                self.progressView.isHidden = false
            }else if self.progressView.progress == 1 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    if self.progressView.progress == 1 {
                        self.progressView.progress = 0
                        self.progressView.isHidden = true
                    }
                }
            }
        }else if "title" == keyPath {
            
            self.title = webView.title
        }
        
        let removeElement = KMTool.removeHtmlElement(classNames: self.removeElements)
        webView.evaluateJavaScript(removeElement, completionHandler: nil)
        let removeId = KMTool.removeHtmlElementForId(idNames: self.removeIds)
        webView.evaluateJavaScript(removeId, completionHandler: nil)
    }
    

}

extension CardOfferViewController : WKNavigationDelegate,WKUIDelegate {
    
    //MARK: 页面加载失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
        KMTool.showText(_text: global_requestFailed)
    }
    
    
    
    //MARK: 页面加载成功
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        let removeElement = KMTool.removeHtmlElement(classNames: self.removeElements)
        webView.evaluateJavaScript(removeElement, completionHandler: nil)
        let removeId = KMTool.removeHtmlElementForId(idNames: self.removeIds)
        webView.evaluateJavaScript(removeId, completionHandler: nil)
        KMTool.showText(_text: global_loadSuccess)
        
    }
    
    //MARK: 拦截网页点击事件
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        let urlString = navigationResponse.response.url?.absoluteString
        
        if urlString! == self.urlStr {
            decisionHandler(.allow)
            return
        }
        
        if (urlString?.contains(webUrl + "/myouhuisdetail/"))! {
            
            
            let webVC = CardOfferViewController.init(urlStr: urlString!, title: self.title!)
            webVC.removeElements = ["mblock mblocks","app-download","footer"]
            self.navigationController?.pushViewController(webVC, animated: true)
            decisionHandler(.cancel)
            return
        }
        
        if (urlString?.contains(webUrl + "/mobile/details/"))! {
            
            
            let webVC = WebViewController.init(urlString: urlString)
            webVC.isSpecial = true
            self.navigationController?.pushViewController(webVC, animated: true)
            decisionHandler(.cancel)
            return
        }
        
        
        decisionHandler(.allow)
    }
}
